<?php

namespace Admin\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Admin\Model\Gallery;
use Admin\Model\Photo;
use Admin\Form\GalleryForm;
use Zend\Db\Sql\Select;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\Iterator as paginatorIterator;
use Zend\Session\Container;
use Zend\Validator\File\Size;
use Zend\Validator\File\Extension;


class GalleryController extends AbstractActionController {

    protected $photoTable;
	protected $galleryTable;

	public function kiemtra(){
		$module = "gallery";
		$controller = $this->params('controller');
		$action = $this->params('action');
		
		$sessionModule = new Container('module');
		$sessionController = new Container('controller');
		$sessionAction = new Container('action');
		$sessionModule->lastModule = $module;
		$sessionController->lastController = $controller;
		$sessionAction->lastAction = $action;
		
		$sessionUser = new Container('user');
		if(!$sessionUser->tendangnhap){
			return $this->redirect()->toRoute('auth');
		}
		else if($sessionUser->tendangnhap && $sessionUser->quyen != 1){
			return $this->redirect()->toRoute('home');
		}
	}
    

    public function addAction() {
		
		$this->kiemtra();
		$id = (int) $this->params('id');
        if (!$id) {
            return $this->redirect()->toRoute('photo', array('action' => 'add'));
        }
		$gal = $this->getGalleryTable()->getGallery($id);
		if (!$gal) {
            return $this->redirect()->toRoute('photo');
        }
		
		$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $form = new GalleryForm($dbAdapter);
		$form->get('id')->setAttribute('value', $id);
		$form->get('tengallery')->setAttribute('value', $gal->tengallery);
        $form->get('submit')->setAttribute('value', 'Cập nhật');
		$viewModel = new ViewModel();
        $request = $this->getRequest();
        if ($request->isPost()) {
			$photo = new Photo();
			$form->setInputFilter($photo->getInputFilter());
			   
			$data = array_merge_recursive(
					$this->getRequest()->getPost()->toArray(),
					$this->getRequest()->getFiles()->toArray()
				);
			  $form->setData($data);
			if ($form->isValid()) {
				$check_rong = 1;
				foreach($data['hinhanh'] as $key3=>$value3){
					if($value3['name']==""){
						$check_rong = 0;
						break;
					}
				}
				if($check_rong == 1){
					$adapter = new \Zend\File\Transfer\Adapter\Http();
				
				
					$size = new Size(array('max'=>5000000)); //minimum bytes filesize
					
					$extension = new Extension(array("extension" => array("jpg", "png", "gif", "jpeg")));
     
	 				$check = 0;
					foreach($data['hinhanh'] as $key2=>$value2){
						$adapter->setValidators(array($size,$extension), $value2['name']);
						if (!$adapter->isValid()){
							$dataError = $adapter->getMessages();
							$error = array();
							foreach($dataError as $key=>$row)
							{
								$error[] = $row;
							} //set formElementErrors
							$form->setMessages(array('hinhanh'=>$error ));
							$check = 1;
							break;
						} 
					}
					if($check==0){
						$adapter->setDestination('public/images/upload');
						
						
						
						
						
						foreach($data['hinhanh'] as $key1=>$value1){
							
							$hinhanh = 'images/upload/'.$value1['name'];
							
							$this->getPhotoTable()->savePhoto(0,$hinhanh,$id);
							
						}
						foreach ($data as $key => $val){
							$adapter->receive($key);
						}
					}
				}
				$this->getGalleryTable()->capnhatGallery($id,$data['tengallery'],$data['mota']);
				return $this->redirect()->toRoute('gallery',array('action' => 'edit','id' =>$id));
			}
            
			
			
			
            
        }

        return array('id' => $id,'form' => $form);
    }

    public function editAction() {
		$this->kiemtra();
		
        $id = (int) $this->params('id');
        if (!$id) {
            return $this->redirect()->toRoute('photo', array('action' => 'add'));
        }
		$viewModel = new ViewModel();
        $photo = $this->getGalleryTable()->getGallery($id);
		if (!$photo) {
            return $this->redirect()->toRoute('photo');
        }

		$request = $this->getRequest();
		if ($request->isPost()) {
			$order_by = $request->getPost('order_by');
			$order = $request->getPost('order');
			$page = $request->getPost('page');
			
			$keyword = $request->getPost('keyword');
			$limit = $request->getPost('limit');
			
			$id = $request->getPost('idgallery');
			
			
			$xoa = $request->getPost('xoa');
			$idxoa = $request->getPost('data');
			if ($idxoa) {
            	$this->getPhotoTable()->deletePhoto($idxoa);
				// Redirect to list of users
				return $this->redirect()->toRoute('photo');
        	}
			
			else if ($xoa!="") {
            	$this->getPhotoTable()->xoaPhoto($xoa);
				return $this->redirect()->toRoute('photo');
        	}
			
			
		
		}
		else{
			$order_by = $this->params()->fromRoute('order_by') ?
                $this->params()->fromRoute('order_by') : 'id';
			$order = $this->params()->fromRoute('order') ?
                $this->params()->fromRoute('order') : Select::ORDER_DESCENDING;
        	$page = $this->params()->fromRoute('page') ? (int) $this->params()->fromRoute('page') : 1;
			
			$keyword = "";
			$limit = "";
		}
        $select = new Select();

        if($limit=="")
		{
			if($keyword!="")
				$gallerys = $this->getPhotoTable()->fetchAll($select->where('gallery = '.$id.' AND (tengallery like "%'.$keyword.'%" OR hoten like "%'.$keyword.'%" )')->order($order_by . ' ' . $order));
			
			else 
				$gallerys = $this->getPhotoTable()->fetchAll($select->where('gallery = '.$id.' AND (tengallery like "%'.$keyword.'%" OR hoten like "%'.$keyword.'%" )')->order($order_by . ' ' . $order));
		}
		else if($limit!="")
		{
			if($keyword!="")
				$gallerys = $this->getPhotoTable()->fetchAll($select->where('gallery = '.$id.' AND (tengallery like "%'.$keyword.'%" OR hoten like "%'.$keyword.'%" )')->order($order_by . ' ' . $order)->limit($limit));
			
			else 
				$gallerys = $this->getPhotoTable()->fetchAll($select->where('gallery = '.$id.' AND (tengallery like "%'.$keyword.'%" OR hoten like "%'.$keyword.'%" )')->order($order_by . ' ' . $order)->limit($limit));
		}
		
		else
        	$gallerys = $this->getPhotoTable()->fetchAll($select->where(array('gallery'=>$id))->order($order_by . ' ' . $order));
        $itemsPerPage = 7;

        $gallerys->current();
        $paginator = new Paginator(new paginatorIterator($gallerys));
        $paginator->setCurrentPageNumber($page)
                ->setItemCountPerPage($itemsPerPage)
                ->setPageRange(7);

        return new ViewModel(array(
                    'order_by' => $order_by,
                    'order' => $order,
                    'page' => $page,
                    'paginator' => $paginator,
					'idgallery' => $id,
					'keyword' => $keyword,
                ));
    }

    public function deleteAction() {
		$this->kiemtra();
		
		$request = $this->getRequest();
		if ($request->isPost()) {
			$id = $request->getPost('data');
			if (!$id) {
            	return $this->redirect()->toRoute('photo');
        	}
			else{
				$this->getPhotoTable()->deletePhoto($id);
				// Redirect to list of users
				return $this->redirect()->toRoute('photo');
			}
		}

        return array(
            'id' => $id,
            'photo' => $this->getPhotoTable()->getPhoto($id)
        );
    }
	public function updateAction() {
		$this->kiemtra();
		
		$request = $this->getRequest();
		if ($request->isPost()) {
			$xoa = $request->getPost('xoa');
			
			if ($xoa!="") {
            	$this->getPhotoTable()->xoaPhoto($xoa);
				return $this->redirect()->toRoute('photo');
        	}
			
			else {
            	return $this->redirect()->toRoute('photo');
        	}
		}

        
    }

    public function getPhotoTable() {
        if (!$this->photoTable) {
            $sm = $this->getServiceLocator();
            $this->photoTable = $sm->get('Admin\Model\PhotoTable');
        }
        return $this->photoTable;
    }
	public function getGalleryTable() {
        if (!$this->galleryTable) {
            $sm = $this->getServiceLocator();
            $this->galleryTable = $sm->get('Admin\Model\GalleryTable');
        }
        return $this->galleryTable;
    }

}
